import axios from 'axios';
import { AadTokenProviderFactory } from '@microsoft/sp-http';
import { ListGUID } from '../webparts/zhuhuaHt/components/config/ListGuid';
export default class DynamicsService {
  private accessToken: string;
  public aadTokenProviderFactory: AadTokenProviderFactory;
  // The resource URI in the above code would be your company’s CRM URI
  public resourceUri: string = 'https://org49f3b3e8.api.crm5.dynamics.com';
  public async setAbort() {
    const controller = new AbortController();
    controller.abort()
  }
  public async getAccessToken() {
    const token = sessionStorage.getItem('dynamic365Token');
    if (token) this.accessToken = token;
    else {
      await this.aadTokenProviderFactory.getTokenProvider().then(tokenProvider => {
        tokenProvider
          .getToken(this.resourceUri)
          .then(t => {
            this.accessToken = t;
            sessionStorage.setItem('dynamic365Token', t);
          })
      });
    }
  }

  public async getAccounts() {
    const url = `${this.resourceUri}/api/data/v9.0/accounts?$top=20&$select=name,emailaddress1`;
    const response = await axios({
      url,
      method: 'GET',
      headers: { Authorization: `Bearer ${this.accessToken}` }
    });
    return response.data.value;
  }

  public async getContacts(id: string) {
    const url = `${this.resourceUri}/api/data/v9.0/contacts?$top=5&$select=fullname,emailaddress1,telephone1,address1_city&$filter=_accountid_value eq '${id}'`;
    const response = await axios({
      url,
      method: 'GET',
      headers: { Authorization: `Bearer ${this.accessToken}` }
    });
    return response.data.value;
  }

  public async searchAccounts(name: string) {
    const url = `${this.resourceUri}/api/data/v9.0/accounts?$top=20&$select=name,emailaddress1&$filter=contains(name,'${name}')`;
    const response = await axios({
      url,
      method: 'GET',
      headers: { Authorization: `Bearer ${this.accessToken}` }
    });
    return response.data.value;
  }
  public async getToken() {
    // const url = `https://139.224.57.135:8002/api/v1/graph/token`;
    const url = `${ListGUID.NETCoreAPIUrl}/api/v1/graph/token`;
    const response = await axios({
      url,
      method: 'GET'
    });
    return response.data;
  }

  public async getList(data) {
    // const url = `https://192.168.124.15:44312/api/Values/GetData`;
    const url = `${ListGUID.requestUrl}/List/GetData`;
    const response = await axios({
      url,
      method: 'POST',
      data
    });
    return response.data;
  }
  public async getListAll(data) {
    // const url = `https://192.168.124.15:44312/api/Values/GetData`;
    const url = `${ListGUID.requestUrl}/List/GetDataAll`;
    const response = await axios({
      url,
      method: 'POST',
      data
    });
    return response.data;
  }
  public async changeData(data) {
    // const url = `https://192.168.124.15:44312/api/Values/GetData`;
    const url = `${ListGUID.requestUrl}/ChangeData/Index?ListGUID=${data.ListGUID}`;
    const response = await axios({
      url,
      method: 'GET',
      data
    });
    return response.data;
  }
  public async getPieCount(data) {
    // const url = `https://192.168.124.15:44312/api/Values/GetData`;
    const url = `${ListGUID.requestUrl}/Home/GetBarData?year=${data.year}&month=${data.month}`;
    const response = await axios({
      url,
      method: 'GET',
      data
    });
    return response.data;
  }
  // https://zhiyi003.weavingbeautiful.vip/Home/GetHistogramData?userName=茫来
  public async GetHistogramData(data) {
    // const url = `https://192.168.124.15:44312/api/Values/GetData`;
    const url = `${ListGUID.requestUrl}/Home/GetHistogramData?userName=${data.userName}`;
    const response = await axios({
      url,
      method: 'GET',
      data
    });
    return response.data;
  }
  // GetLineChatData?users=李虞湮|郑红秋|茫来&startTime=&endTime=
  public async GetLineChatData(data) {
    // const url = `https://192.168.124.15:44312/api/Values/GetData`;
    const url = `${ListGUID.requestUrl}/Home/GetLineChatData?users=${data.users}&startTime=${data.startDate}&endTime=${data.endDate}`;
    const response = await axios({
      url,
      method: 'GET',
      data
    });
    return response.data;
  }
  public async AddContract(data) {
    // const url = `https://192.168.124.15:44312/api/Values/GetData`;
    const url = `${ListGUID.requestUrl}/SyncDataToDB/AddContract`;
    const response = await axios({
      url,
      method: 'POST',
      data
    });
    return response.data;
  }
  public async UpdateContract(data) {
    // const url = `https://192.168.124.15:44312/api/Values/GetData`;
    const url = `${ListGUID.requestUrl}/SyncDataToDB/UpdateContract`;
    const response = await axios({
      url,
      method: 'POST',
      data
    });
    return response.data;
  }
  public async AddRegulation(data) {
    // const url = `https://192.168.124.15:44312/api/Values/GetData`;
    const url = `${ListGUID.requestUrl}/SyncDataToDB/AddRegulation`;
    const response = await axios({
      url,
      method: 'POST',
      data
    });
    return response.data;
  }
  public async UpdateRegulation(data) {
    // const url = `https://192.168.124.15:44312/api/Values/GetData`;
    const url = `${ListGUID.requestUrl}/SyncDataToDB/UpdateRegulation`;
    const response = await axios({
      url,
      method: 'POST',
      data
    });
    return response.data;
  }
  public async AddCase(data) {
    // const url = `https://192.168.124.15:44312/api/Values/GetData`;
    const url = `${ListGUID.requestUrl}/SyncDataToDB/AddCase`;
    const response = await axios({
      url,
      method: 'POST',
      data
    });
    return response.data;
  }
  public async UpdateCase(data) {
    // const url = `https://192.168.124.15:44312/api/Values/GetData`;
    const url = `${ListGUID.requestUrl}/SyncDataToDB/UpdateCase`;
    const response = await axios({
      url,
      method: 'POST',
      data
    });
    return response.data;
  }
  public async GetCheckYear(data) {
    // const url = `https://192.168.124.15:44312/api/Values/GetData`;
    const url = `${ListGUID.requestUrl}/Home/GetCheckYear`;
    const response = await axios({
      url,
      method: 'POST',
      data
    });
    return response.data;
  }
  
  public async UpdateListFileNames(data) {
    // const url = `https://192.168.124.15:44312/api/Values/GetData`;
    const url = `${ListGUID.requestUrl}/SyncDataToDB/UpdateListFileNames?dataid=${data.dataid}&listguid=${data.listguid}&fileaddress=${data.fileaddress}`;
    const response = await axios({
      url,
      method: 'GET',
      data
    });
    return response.data;
  }
  public async DelFile(data) {
    const url = `${ListGUID.requestUrl}/syncapi/SyncDataToSP/DelFile?title=${data.title}&listquid=${data.listquid}`;
    const response = await axios({
      url,
      method: 'GET',
    });
    return response.data;
  }
  public async GetUserPer(data) {
    const url = `${ListGUID.requestUrl}/List/GetUserPermissionProfile?Email=${data.email}`;
    const response = await axios({
      url,
      method: 'GET',
    });
    return response.data;
  }
  public async getAllFileQuery(data) {
    const url = `${ListGUID.requestUrl}/List/GetSearchAsync?search=${data.search}`;
    const response = await axios({
      url,
      method: 'POST',
      data: data.data
    });
    return response.data;
   
  }
  public async GetPetitionMonth(data) {
    const url = `${ListGUID.requestUrl}/Home/GetPetitionMonth?Email=${data.email}`;
    const response = await axios({
      url,
      method: 'GET',
    });
    return response.data;
  }
  public async getusers(name: string) {
    const url = `${ListGUID.GraphApiEndPoint}/v1.0/users/?%24select=displayName%2CcompanyName%2Cdepartment`;
    const response = await axios({
      url,
      method: 'GET',
      headers: { Authorization: `${name}` }
    });
    return response.data;
  }
  public async getAADUsers() {
    const url = `${ListGUID.GraphApiEndPoint}/v1.0/users/?$select=displayName,companyName,department,mail,jobTitle&$top=500`;

    let token = await this.getToken();
    let aadUsers = [];
    const response = await axios({
      url,
      method: 'GET',
      headers: { Authorization: `${token.data.data}` }
    });

    let nextRequesUrl = '';
    let v1 = response.data;
    let index = 2;
    nextRequesUrl = v1['@odata.nextLink'];
    if (v1.value && v1.value.length > 0) {
      let data1 = v1.value;
      data1.forEach(element => {
        let currentEmail = element.mail;
        //邮箱没有的忽略
        if (currentEmail != '' && currentEmail != null) {
          let addObj = {
            displayName: element.displayName,
            companyName: element.companyName,
            department: element.department,
            mail: element.mail,
            jobTitle: element.jobTitle,
            usercode: ''
          };
          let userCodeArr = currentEmail.split('@'); //baoqw@SCEM-CN.COM   baoanshi@wxsem.com
          if (userCodeArr && userCodeArr.length > 1) {
            let userCode = userCodeArr[0].toLowerCase();
            addObj.usercode = userCode;
          }
          aadUsers.push(addObj);
        }
      });
    }

    while (nextRequesUrl != '' && nextRequesUrl != undefined) {
      const _thisRespose = await axios({
        url: nextRequesUrl,
        method: 'GET',
        headers: { Authorization: `${token.data.data}` }
      });

      let v2 = _thisRespose.data;
      nextRequesUrl = v2['@odata.nextLink'];

      if (v2.value && v2.value.length > 0) {
        let data1 = v2.value;
        data1.forEach(element => {
          let currentEmail = element.mail;
          //邮箱没有的忽略
          if (currentEmail != '' && currentEmail != null) {
            let addObj = {
              displayName: element.displayName,
              companyName: element.companyName,
              department: element.department,
              mail: element.mail,
              jobTitle: element.jobTitle,
              usercode: ''
            };
            let userCodeArr = currentEmail.split('@'); //baoqw@SCEM-CN.COM   baoanshi@wxsem.com
            if (userCodeArr && userCodeArr.length > 1) {
              let userCode = userCodeArr[0].toLowerCase();
              addObj.usercode = userCode;
            }
            aadUsers.push(addObj);
          }
        });
      }

      //TODO: 将 v2。value  值进行code的拆解，然后添加到集合中，然后增加缓存中，然后部门那里进行匹配
      //然后把这个放到 韩爷的入口文件，进行调用下就OK
      index++;
      if (index == 10) {
        //每次取500  最多取10次 即5000人即可
        nextRequesUrl = ''; //强行让10次就退出；
      }
    }

    //存入session
    sessionStorage.setItem('AADUsers', JSON.stringify(aadUsers));

  }

  public async getFileContentByGraphApi(requestBody: {}) {
    //Graph API 调用方式
    // let keys = keyWords.split(' ');
    // let searchKeyArr: string[] = [];
    // for (let index = 0; index < keys.length; index++) {
    //   const keyWord = keys[index];
    //   if (keyWord == '') {
    //     continue;
    //   }
    //   searchKeyArr.push(keyWord);
    // }
    // let strKey: string = searchKeyArr.join(' OR ');

    // //查询附件
    // let requestBody = {
    //   requests: [
    //     {
    //       entityTypes: ['listItem'],
    //       query: {
    //         queryString: `${strKey} path:\"${searchLibUrl}\"`
    //       }
    //     }
    //   ]
    // };

    let token = await this.getToken();
    const url = `${ListGUID.GraphApiEndPoint}/v1.0/search/query`;
    const response = await axios({
      url,
      method: 'POST',
      headers: { Authorization: `Bearer ${token.data.data}` },
      data: requestBody
    });
    return response.data;
  }

  public async getFileContentByCSOMApi(querytext: string, doclibidentification: string) {
    const url = `${ListGUID.NETCoreAPIUrl}/api/v1/search/query?querytext=${querytext}&doclibidentification=${doclibidentification}`;
    const response = await axios({
      url,
      method: 'GET'
    });
    return response.data.data;
  }
}
